package com.pozu.new_retail.dao.base;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;

/**
 * @author ChaoDaiJin
 * @description 跨域解决方案
 * @date 2017年5月27日 上午11:46:25
 */
public class CorsFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		// 指定允许其他域名访问
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		// 响应类型
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
		// 响应头设置
		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, userId,appId");
		if ("OPTIONS".equals(request.getMethod())){
			response.setStatus(HttpStatus.SC_NO_CONTENT);
		} 
		chain.doFilter(arg0, arg1);
		
	}
	
	public void destroy() {
		
	}

}
